<!--
* description: 基础数据-故障原因码新增/修改
* author: wangjuan
* createdDate: 2021-5-6
-->
<template>
  <section class="editFinancialMonthlyMaintenance">
    <el-dialog
      v-dialogDrag
      :visible.sync="curPopupsVisible"
      :title="textMap[popupsState]"
      :append-to-body="true"
      width="50%"
      :close-on-click-modal="false"
      @close="closeEdit"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents.filter(o => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds || ''"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 8"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
          />
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from '@/components/mixins/formMixins'
import api from '@/api/se/apiBaseData'

export default {
  components: {
    dialogHeader: () => import('@/components/dialogHeader')
  },

  // 组件混入对象
  mixins: [formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: { type: Object, default: function() { return {} } }
  },

  data() {
    const viewPageCode = 'FinancialMonthlyMaintenance-edit'

    return {
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.save(),
          text: this.$t('sys.button.save') /* 保存*/,
          position: 'right'
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          icon: 'iconfont  icon-cancel',
          clickEvent: () => this.closeEdit(1),
          text: this.$t('sys.button.cancel') // 取消
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '故障原因码：',
              codeField: 'faultRcCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              disabled: false,
              isMul: false,
              isMust: true,
              validrule: {
                isformat: /^[A-Za-z0-9]+$/,
                maxlength: 20,
                resectMessage: {
                  isformat: '请输入由数字和英文字母（不区分大小写）组成的密码!'
                }
              },
              span: 12
            },
            {
              compKey: 'compKey2',
              labelName: '故障原因名称：',
              codeField: 'faultRcName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 12
            },
            {
              compKey: 'compKey3',
              labelName: '备注：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput/textareaInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 24
            }
          ],

      // 标题
      textMap: {
        edit: '故障原因编辑',
        add: '故障原因新增'
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(this, {
        faultRcCode: '',
        faultRcName: '',
        remark: '',
        faultRcId: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },

  watch: {
    curPopupsVisible: {
      handler: function(val) {
        if (val) {
          if (this.popupsState === 'edit') {
            this.tableComponents[0].disabled = true
          } else {
            this.tableComponents[0].disabled = false
          }
        }
      }
    }
  },
  methods: {
    // 新增/编辑保存按钮
    save() {
      const that = this
      this.$utils.validataMoth(this, 'validpopup')
      if (this.valid) {
        if (that.popupsState === 'edit') {
          that.editSave()
        } else {
          that.addSave()
        }
      }
    },

    // 编辑保存
    editSave() {
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api.editFaultRc,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField

      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.$emit('update:popupsVisible', false)
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    // 新增保存
    addSave() {
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api.addFaultRc,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.$emit('update:popupsVisible', false)
          this.$nextTick(() => {
            this.$parent.$refs.multipleTable.queryTable(1)
          })
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    closeEdit() {
      this.$emit('update:popupsVisible', false)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>

